package cn.gwm.flink.streaming.dwd.standardization;

import cn.gwm.flink.streaming.constant.BusinessUrl;
import cn.gwm.utils.ConfigLoader;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: liangguang
 * @Date: 2023/01/15
 * @Description: 标准化字段转换类
 */
public class StandardFieldTrans {

    private static Long lastUpdateTime = DateUtil.lastMonth().getTime();

    private static Long longTime = 24 * 60 * 60 * 1000L + RandomUtil.randomLong(200000);


    /**
     * key - 车型
     * <p>
     * key  标准化字段
     * value 原始字段
     */
    private static Map<String, Map<String, String>> fieldMap = new ConcurrentHashMap<>();


    public static Map<String, String> getFieldMap(String vehicleType, String customType) {
        if (!fieldMap.containsKey(vehicleType)) {
            query(vehicleType, customType);
        } else if (System.currentTimeMillis() - lastUpdateTime > longTime) {
            // 更新即可
            query(vehicleType, customType);
            lastUpdateTime = System.currentTimeMillis();
        }
        return fieldMap.get(vehicleType);
    }


    public static void query(String vehicleType, String customType) {
        Map<String, Object> param = new HashMap<>();
        param.put("vehicleTypes", Arrays.asList(customType, vehicleType));
        String s = HttpUtil.get(ConfigLoader.get("charging.station.type.url") + BusinessUrl.STANDARD_FIELD_CHANGE_URL, param);
        JSONObject parseObj = JSONUtil.parseObj(s);
        Map<String, String> result = new ConcurrentHashMap<>();

        try {
            if (parseObj.getInt("code") == 200) {
                JSONArray array = parseObj.getJSONArray("data");
                if (array.size() > 0) {
                    array.forEach(item -> {
                        String original = ((JSONObject) item).getStr("original");
                        String standard = ((JSONObject) item).getStr("standard");
                        result.put(standard, original);
                    });
                }
            }
            fieldMap.put(vehicleType, result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
